package com.xjoyt.pay.share.api.email;

import java.util.Properties;

import org.apache.commons.lang3.StringUtils;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Component;

import com.xjoyt.pay.dto.ExecuteResult;
import com.xjoyt.pay.share.dto.EmailSendResult;
import com.xjoyt.pay.share.params.EmailParam;

@Component
public class EmailClient {

	public ExecuteResult<EmailSendResult> send(EmailParam param, String code) {
		SimpleMailMessage message = new SimpleMailMessage();
		if (StringUtils.isBlank(param.from) || StringUtils.isBlank(param.to)) {
			return ExecuteResult.fail();
		}
		message.setFrom(param.from);
		message.setTo(param.to);
		message.setSubject(param.sign);

		String content = String.format("邮件验证码。您的验证码为：%s", code);
		message.setText(content);

		JavaMailSenderImpl sender = new JavaMailSenderImpl();
		sender.setHost(param.host);
		sender.setUsername(param.userName);
		sender.setPassword(param.password);

		Properties properties = new Properties();
		properties.put("mail.smtp.auth", true);
		properties.put("mail.smtp.starttls.enable", true);
		properties.put("mail.smtp.timeout", 5000);
		sender.setJavaMailProperties(properties);
		try {
			sender.send(message);
		} catch (Exception e) {
			return ExecuteResult.fail("邮件发送异常");
		}

		EmailSendResult result = new EmailSendResult();
		result.content = content;
		result.value = code;
		return ExecuteResult.ok(result);
	}

}
